#include "BidirectionImpl.h"
#include <Ice/Connection.h>
#include <BirConnection.h>

void Demo::CallbackReceiverImpl::callback(::Ice::Int num, const Ice::Current& current)
{
	std::cout << "Client:" << num << std::endl;
}


void Demo::CallbackSenderImpl::removeClient(const std::string& _clientID)
{
	std::unique_lock<std::mutex> lock(m_ClientsMutex);
	if (m_Clients.find(_clientID) == m_Clients.end())
		return;
	if (m_idClientInfoMap.find(_clientID) == m_idClientInfoMap.end())
		return;
	ClientInfo& clientInfo = m_idClientInfoMap[_clientID];
	std::cout << "移除的客户端ID:【" << _clientID << "】,ip地址:【" << clientInfo.mIP << "】,端口号【" << clientInfo.mPort << "】" << std::endl;

	m_Clients.erase(_clientID);
	m_idClientInfoMap.erase(_clientID);
}


Demo::CallbackSenderImpl::CallbackSenderImpl()
{
	m_WorkThread = std::thread(std::bind(&Demo::CallbackSenderImpl::loop, this));
}

Demo::CallbackSenderImpl::~CallbackSenderImpl()
{
	m_ExitFlag = false;
	m_WorkThread.join();
}

void Demo::CallbackSenderImpl::loop()
{
	while (m_ExitFlag) {
		Sleep(5000);
		notifyClients();
	}
}

void Demo::CallbackSenderImpl::addClient(const ::Ice::Identity& ident, const Ice::Current& current)
{
	const std::string guid = ident.name;
	CallbackReceiverPrx client = CallbackReceiverPrx::uncheckedCast(current.con->createProxy(ident));
	::Ice::ConnectionPtr conn = current.con;
	if (!conn)
		return;
	//表示客户端到服务器的连接空闲num秒后就会自动关闭,再次通讯时又会连接上
	conn->setACM(15, ::IceUtil::None, ::IceUtil::None);

	const ::Ice::ConnectionInfoPtr connInfo = conn->getInfo();
	::Ice::IPConnectionInfoPtr ipInfo = ::Ice::IPConnectionInfoPtr::dynamicCast(connInfo);

	std::string ip = ipInfo->remoteAddress;
	std::string port = std::to_string(ipInfo->remotePort);
	ClientInfo clientInfo(ip, port);

	std::cout << "注册【" << guid << "】客户端" << std::endl;
	std::unique_lock<std::mutex> lock(m_ClientsMutex);
	m_Clients[guid] = client;
	m_idClientInfoMap[guid] = clientInfo;
}

void Demo::CallbackSenderImpl::notifyClients()
{
	std::unique_lock<std::mutex> lock(m_ClientsMutex);
	auto iter = m_Clients.begin();
	while (iter != m_Clients.end()) {
		try {
			CallbackReceiverPrx client = iter->second;
			client->callback(10);
			iter++;
		}
		catch (const ::Ice::Exception& ex) {
			std::cout << "Ice异常:" << ex.what() << std::endl;

			const std::string guid = iter->first;
			ClientInfo& clientInfo = m_idClientInfoMap[guid];
			std::cout << "移除的客户端ID:【" << guid << "】,ip地址:【" << clientInfo.mIP << "】,端口号【" << clientInfo.mPort << "】" << std::endl;
			m_Clients.erase(iter++);
			m_idClientInfoMap.erase(guid);
		}
	}
}


void Demo::CallbackSenderImpl::registerConntionHandler(const ::std::string& clientId, const::Ice::Current & current)
{
	std::cout << "注册断线通知" << std::endl;
	Ice::ConnectionPtr connection = current.con;
	connection->setACM(15, ::Ice::CloseOnInvocationAndIdle, ::Ice::HeartbeatAlways);
	connection->setCallback(new BirConnection(clientId, this));
}
